import axios from 'axios'
import {baseURL} from './baseURL'
import { Dialog } from 'vant'
import router from '../router'
import Vue from 'vue'
import { sync } from 'rimraf'

axios.defaults.withCredentials=true;

const request = axios.create({ 
    baseURL
})

const refreshTokenReq = axios.create({ 
    baseURL
})

request.interceptors.request.use(function (config) {
    let result = JSON.parse(window.localStorage.getItem("result"))
    if(result){ 
        config.headers.Authorization = "Bearer " + result.token
    }

    return config
    
    },function (error) { 
        return Promise.reject(error)
    }
)


request.interceptors.response.use(function (response) {  
        return response
    },
    async function(err) {
        let status = err.response.status
        let result = JSON.parse(window.localStorage.getItem("result"))
        if(status === 401) {     
            // Dialog({
            //     message:'登录状态过期'
            // }).then(() => { 
            //     window.localStorage.removeItem("result")
            //     window.localStorage.removeItem("Message")
            //     Vue.prototype.websocket.forceClose();
            //     setTimeout(() => {
            //         router.push("/login")
            //     }, 310);
            // })

            if(!result){ 
                Vue.prototype.websocket.forceClose();
                return router.replace("/login")
            }

            try {
                //刷新token
                const { data } = await refreshTokenReq({ 
                    method:'put',
                    url:'/token/refreshToken',
                    headers:{ 
                        Authorization: "Bearer " + result.refresh_token,
                    }
                })
                

                //刷新回来的token更新到本地存储上
                result.token = data;
                window.localStorage.setItem("result",JSON.stringify(result));
                
                return request(err.config);

            } catch (error) {
                Vue.prototype.websocket.forceClose();
                return router.replace("/login")
            }
        }

        return Promise.reject(err)
    }
)

export default request